//
//  LXSaveViewController.m
//  喜马拉雅改良版框架
//
//  Created by liuxin on 15/12/29.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "LXSaveViewController.h"
#import "LXSaveModel.h"
#import "LXSaveTableViewCell.h"
#import "CoreDataManager.h"
#import "Album.h"
@interface LXSaveViewController ()<UITableViewDataSource,UITableViewDelegate,LXSaveModelDelegate>
@property(nonatomic,retain)NSManagedObjectContext *managerObjectContext;
@property(nonatomic,strong)UITableView *myTableView;
@property(nonatomic,strong)NSMutableArray *saveArray;
@property(nonatomic,strong)NSMutableArray *allArray;
@end

@implementation LXSaveViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self selectAll];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _managerObjectContext = [[CoreDataManager shareManager]managedObjectContext];
//    NSLog(@"%@",[[CoreDataManager shareManager]applicationDocumentsDirectory]);
    self.allArray  = [NSMutableArray array];
    self.saveArray = [NSMutableArray array];
    self.view.backgroundColor = [UIColor whiteColor];
    self.isUpLoad = NO;
    [self createTableView];
    [self getData];
    [self addHeaderRefresh];
}
-(void)getData{
    NSString *strUrl = @"http://mobile.ximalaya.com/mobile/album/recommend/list/unlogin?device=iPhone";
    [AFNetworkTool getUrl:strUrl body:nil result:HXJSON headerFile:nil success:^(id result) {
        NSString *str = @"";
        for (NSDictionary *dic in result[@"frDatas"]) {
            LXSaveModel *temp = [LXSaveModel new];
            [temp setValuesForKeysWithDictionary:dic];
            for (Album *tempA in self.saveArray) {
                if ([tempA.albumId integerValue] == temp.albumId ) {
                    str = @"yes";
                }else{
                     str = @"no";
                }
            }
            if (![str isEqualToString:@"yes"]) {
                [self.allArray addObject:temp];
            }
        }
        NSLog(@"self.allArray count == %ld",self.allArray.count);
        /** 结束刷新状态 */
       [self.myTableView reloadData];
       [self.myTableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
    }];
}
-(void)selectAll{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Album" inManagedObjectContext:_managerObjectContext];
    [fetchRequest setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    NSError *error = nil;
    NSArray *fetchedObjects = [_managerObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"%@",error);
    }
    self.saveArray = [NSMutableArray arrayWithArray:fetchedObjects];
}
-(void)createTableView{
    self.myTableView = [[UITableView alloc]init];
    [self.view addSubview:self.myTableView];
    self.myTableView.backgroundColor = [UIColor whiteColor];
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.offset(0);
        make.bottom.offset(-49);
    }];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.myTableView registerClass:[LXSaveTableViewCell class] forCellReuseIdentifier:@"cell"];
}
-(void)addHeaderRefresh{
    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
    }];
//     设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(HeaderRefresh)];
    // 马上进入刷新状态
    [self.myTableView.mj_header beginRefreshing];
}
-(void)HeaderRefresh{
    [self.allArray removeAllObjects];
    [self selectAll];
    [self getData];
}
//-(void)addFooterRefresh{
//    self.myTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        // 进入刷新状态后会自动调用这个block
//        NSLog(@"上拉");
//        self.isUpLoad = YES;
//        self.page++;
//        // 重新请求数据
//        [self getData];
//    }];
//}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.saveArray.count == 0) {
        return 1;
    }else{
    return 2;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.saveArray.count == 0) {
        return _allArray.count;
    }else{
    if (section == 0) {
        return _saveArray.count;
    }else{
        return _allArray.count;
    }
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 25;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 25)];
    headView.backgroundColor = [UIColor colorWithWhite:0.835 alpha:1.000];
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:headView.bounds];
    titleLabel.textColor = [UIColor grayColor];
    if (self.saveArray.count == 0) {
        titleLabel.text = @" 推荐收藏";
    }else{
    if (section == 0) {
        titleLabel.text = @" 我的收藏";
    }else{
        titleLabel.text = @" 推荐收藏";
    }
    }
    [headView addSubview:titleLabel];
    return headView;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.saveArray.count == 0) {
        LXSaveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.saveDelegate = self;
        cell.from = @"save";
        cell.index = indexPath.row;
        cell.section = indexPath.section;
        cell.cellModel = [_allArray objectAtIndex:indexPath.row];
        return  cell;
    }else{
    if (indexPath.section == 0) {
        LXSaveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.saveDelegate = self;
        cell.from = @"delete";
        cell.index = indexPath.row;
        cell.section = indexPath.section;
        cell.cellModel = [_saveArray objectAtIndex:indexPath.row];
        return  cell;
    }else{
    LXSaveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.saveDelegate = self;
    cell.from = @"save";
    cell.index = indexPath.row;
    cell.section = indexPath.section;
    cell.cellModel = [_allArray objectAtIndex:indexPath.row];
    return  cell;
    }
    }
}
-(void)bringSaveOrDelete:(LXSaveModel *)bringModel type:(NSString *)type index:(NSInteger)index section:(NSInteger)section{
    if ([type isEqualToString:@"save"]) {
        Album *album = [NSEntityDescription insertNewObjectForEntityForName:@"Album" inManagedObjectContext:_managerObjectContext];
        album.uid = [NSNumber numberWithInteger:bringModel.uid];
        album.albumId = [NSNumber numberWithInteger:bringModel.albumId];
        album.title = bringModel.title;
        album.coverMiddle = bringModel.coverMiddle;
        album.updatedAt = [NSNumber numberWithInteger:bringModel.updatedAt];
        album.tracks = [NSNumber numberWithInteger:bringModel.tracks];
        album.nickname = bringModel.nickname;
        album.avatar = bringModel.avatar;
        album.lastUptrackTitle = bringModel.lastUptrackTitle;
        album.lastUptrackAt = [NSString stringWithFormat:@"%@",bringModel.lastUptrackAt];
        album.intro = bringModel.intro;
        [[CoreDataManager shareManager]  saveContext];
    }else{
        if (section == 1) {
            [self selectAll];
            for (Album *temp in self.saveArray) {
                if ([temp.title isEqualToString:bringModel.title]) {
                    [_managerObjectContext deleteObject:temp];
                    [[CoreDataManager shareManager]saveContext];
                    [self selectAll];
                    [self.myTableView reloadData];
                }
            }
        }else{
        Album *temp = [_saveArray objectAtIndex:index];
        [_managerObjectContext deleteObject:temp];
        [[CoreDataManager shareManager]saveContext];
        [_saveArray removeObjectAtIndex:index];
        [self.myTableView reloadData];
        }
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
